
import requests
from flask import request, render_template

from app.web.casesuit.get_token import GetToken
from app.web.casesuit.add_project import Project
from app.web.casesuit.get_client import  GetClient
from app.web.casesuit.sql_select import  get_client_id
# from casesuit.cloud_platform.test_merchant_platform import test_projectlist
from app.web.comm.merchant_platform import  test_projectlist
from app.web.conf.config import *
from app.web.casesuit.test_merchant_platform import  *
from . import web
from app.web.comm.encry import  *
# base_url_c="http://shanghu-mp-dev.wetax.com.cn/v3/scan-qrcode/commit-static"
#pc在线开票
#在线人工开票
client_id='12835'
store_id='16474'
G=GetToken()
requests.packages.urllib3.disable_warnings()  # Python的第三方库requests提示警告InsecureRequestWarning的问题

@web.route("/invoice")
def invoice_index():
    pass
    return render_template('invoice.html')


def project_list(self,token_pc):#查询商品编码是否为空
    url=base_url_cloud +"/client-project/projects?token=%s"%self.token_pc
    request_data={"page_size":10}
    res=requests.post(url=url,data=request_data, verify=False)
    project_list=res.json()['data']['list']
    # return project_list
    if project_list ==[]:
        print("还未设置开票项目")
        Project().add_project()
        print("添加开票项目成功！")

    else:
        print("已设置开票项目")

"""在线（单张）开票"""
@web.route('/invoice/online_invoice', methods=['GET', 'POST'])

def online_invoice(title="在线开电票",invoice_style=1):
    if request.method == "POST":
        tax_code=request.values.get("tax_code")
        password=request.values.get("password")
        tax_code_r=AES_Encrypt(data=tax_code)
        password_r=AES_Encrypt(data=password)
        token_pc = G.login_token(tax_code_r,password_r)
        # token_pc ="CtoosNnbq6mtqIL14s0JhKkgYNwCvmdftFcPbfnX"
        url=base_url_cloud+"/v3/online-invoicing/blue?token=%s"%token_pc
        print("在线开票请求url：%s" % url)
        # tax_num_store = GetClient().get_store_equipment(store_id=store_id)

        data = {
            "buyer_title_type":2,
            "buyer_title":"单张开电票",
            "buyer_taxcode":"91469027MA5RH09M0R",
            "buyer_email":"",
            "buyer_address":"大冲恒大华府",
            "buyer_phone":"1788888999",
            "buyer_bank_name":"中国银行·",
            "buyer_bank_account":"7878575757577575757",
            "seller_name":"",
            "taxpayer_num":"",
            "seller_address":"",
            "seller_tel":"",
            "seller_bank_name":"",
            "seller_bank_account":"",
            "goods_info":[{
                "name":"住宿服务",
                "models":"豪华",
                "unit":"天",
                "total":0.2,
                "price":272.64150943,
                "price_with_tax":289,
                "total_price":"54.53",
                "total_price_with_tax":"57.80",
                "tax_rate":"6%",
                "tax_amount":"3.27",
                "id":7186,
                "tax_code":"3070402000000000000",
                "firm_goods_no":"3070402000000000000",
                "firm_goods_name":"住宿服务",
                "is_default":0,
                "per_price":289,
                "vat_special_manager":"",
                "zero_tax_flag":"",
                "special_invoice_kind":"",
                "description":"测试",
                "_key":"coSIJRgaWpXUv1H3"
            }],
            "payee":"",
            "reviewer":"",
            "drawer":"开票员",
            "remark":"测试",
            "total_tax":"1.64",
            "total_price":"27.26",
            "total_price_with_tax":"28.90",
            "total_rmb":"贰拾捌圆玖角",
            "store_id":"",
            "invoice_style":invoice_style ,
            "tax_num_id":"",
            "title_type":2,
            "amount":"28.90",
            "extra":"测试"
        }
        datas = GetClient().client_details(token_pc)
        test_datalist(datas, data)#补充商户信息
        projects = GetClient().project_details_default(token_pc)
        # test_projectlist(projects,data["goods_info"][0])#替换data里面的开票项为商户的默认开票项
        # data['tax_num_id']=GetClient().get_equipment(self.token_pc)#税盘id
        store_id=GetClient().get_store_list(token_pc)#获取门店id#
        data['store_id'] = store_id
        data['tax_num_id']=GetClient().get_store_equipment(store_id,token_pc,invoice_style)#获取穗盘id
        #(self,store_id,token_pc,invoice_style=0,No=0)
        print("单张开票提交开票请求数据：{}".format(data))
        headers = {"Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=UTF-8"}
        response = requests.post(headers=headers, url=url, json=data, verify=False)
        # print(response)
        print(response.json())
        try:
            r = response.json()['data']['InvoiceCommitLogic']['data']['order_sn']
            order_sn = r
            print('在线订单号：%s' % order_sn)
            # context=order_sn
            # return ("单张开票成功:%s"%order_sn )
            return render_template('invoice.html', context="在线开票单号："+order_sn)

        except:
            # print("在线开票失败")
            return("在线开票失败。。。")
        # return render_template('invoice.html')


    #     return ("单张开票成功",order_sn )
    # else:
    #     return ("单张开票失败")

@web.route('/invoice/scan_invoice',methods=['GET','POST'])
def sweep_code(invoice_style="a", title="固定码开票电票"):  # 扫码并提交(企业),invoice_type=a 表示电票，b表示普通纸票，g表示卷票
    if request.method == "POST":
        tax_code=request.values.get("tax_code")
        password=request.values.get("password")
        token_c=request.values.get("token_c")
        tax_code_r=AES_Encrypt(data=tax_code)
        password_r=AES_Encrypt(data=password)

        token_pc = G.login_token(tax_code_r, password_r)

        url=base_url_c_new+"/v3/scan-qrcode/commit-static?_v=3.7&token=%s"%token_c
        print("扫码提交开票请求url：%s" % url)
        data = {
            "form_id":"formId",
            "buyer_title_type":"2",
            "buyer_title":"广州腾讯科技有限公司",
            "buyer_taxcode":"91440101327598294H",
            "buyer_address":"广州市海珠区新港中路397号自编72号(商业街F5-1)",
            "buyer_address_phone":"020-81167888",
            "buyer_bank_name":"招商银行股份有限公司广州市体育东路支行",
            "buyer_bank_account":"120909282210301",
            "buyer_phone":"",
            "buyer_email":"jenny.zhang@wetax.com.cn",
            "remark":"",
            "client_id":"12835",
            "store_id":"16109",
            "invoice_style":"a",
            "is_auth":0,
            "amount":"46"
        }
            # test_datalist(client_datas, data)#
        data['client_id']=GetClient().get_client_id(tax_code)
        data['store_id'] = GetClient().get_store_list(token_pc)
        print("扫码提交开票请求数据：{}".format(data))
        headers = {"Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=UTF-8"}
        response = requests.post(headers=headers, url=url, json=data, verify=False)
        print(response.json())
        try:
            r = response.json()['data']['order_sn']
            order_sn1 = r
            print('固定码订单号：%s' % order_sn1)
            return render_template('invoice.html', context1="固定码扫码单号："+order_sn1)
        except:
            return ("扫码提交生成订单失败了。。。")

    #     return ("扫码提交开票单号",order_sn )
    # else:
    #     return ("扫码提交开票失败！")


    """创建小票码"""
@web.route('/invoice/create_code',methods=['GET','POST'])
def create_code():#生成小票码
    if request.method == "POST":
        tax_code=request.values.get("tax_code")
        password=request.values.get("password")
        tax_code_r=AES_Encrypt(data=tax_code)
        password_r=AES_Encrypt(data=password)
        token_pc = G.login_token(tax_code_r,password_r)

        url=base_url_cloud+"/v3/code-order/create?sid=&token=%s"%token_pc
        data ={
            "seller_name":"",
            "taxpayer_num":"",
            "seller_address":"浙江省嘉兴市海宁市海洲街道海昌南路509号16层",
            "seller_tel":"17665566611",
            "seller_bank_name":"招商银行",
            "seller_bank_account":"123456788",
            "goods_info":[{"name":"文化服务","models":"","unit":"","total":1,"price":1.16037736,
                           "price_with_tax":1.23,"total_price":"1.16","total_price_with_tax":"1.23",
                           "tax_rate":"6%","tax_amount":"0.07","id":7372,"tax_code":"3070101000000000000",
                           "firm_goods_no":"3070101000000000000","firm_goods_name":"文化服务","is_default":0,
                           "per_price":0,"vat_special_manager":"免税","zero_tax_flag":"","special_invoice_kind":"",
                           "description":"","_key":"oe591c2VzpcZNUeV"}],
            "payee":"收款的",
            "reviewer":"测试",
            "drawer":"test940",
            "remark":"ces",
            "total_tax":"0.07",
            "total_price":"1.16",
            "total_price_with_tax":"1.23",
            "total_rmb":"壹圆贰角叁分",
            "invoice_style":0,
            "invalid_at":30,
            "consumer_phone":"",
            "store_id":16761,
            "tax_num_id":8798,
            "title_type":2,
            "amount":"1.23",
            "invoicer":"test940",
            "extra":"ces"
        }
        datas = GetClient().client_details(token_pc)
        # print(datas)
        test_datalist(datas, data)#补充商户信息
        projects = GetClient().project_details_default(token_pc)
        test_projectlist(projects,data["goods_info"][0])#替换data里面的开票项为商户的默认开票项
        # data['client_id']=GetClient().get_client_id(self.tax_code)
        data['store_id'] = GetClient().get_store_list(token_pc)#获取门店id
        print("生成小票码请求数据：{}".format(data))
        headers = {"Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=UTF-8"}
        response = requests.post(headers=headers, url=url, json=data, verify=False)
        print(response.json())
        re=response.json()
        order_sn2=re['data']['order_sn']
        # return("创建小票码成功，单号：%s"%re['data']['order_sn'])
        return render_template('invoice.html', context2="创建小票码单号："+order_sn2)
    else:
        return("创建小票码失败")


